package com.example.helpconnect;

import java.text.NumberFormat;

import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.widget.EditText;

public class CostTextWatcher implements TextWatcher {
	
	private EditText costField;

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// Do nothing
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		if(!s.toString().matches("^\\$(\\d{1,3}(\\,\\d{3})*|(\\d+))(\\.\\d{2})?$")) {
            String userInput= ""+s.toString().replaceAll("[^\\d]", "");
            Float in=Float.parseFloat(userInput);
            float percen = in/100;     
            String cost = NumberFormat.getCurrencyInstance().format(percen);

			costField.removeTextChangedListener(this);
            costField.setTextKeepState(cost);
            Selection.setSelection(costField.getText(), cost.length());
			costField.addTextChangedListener(this);
        }
	}

	@Override
	public void afterTextChanged(Editable s) {
		// Do nothing
	}

	public EditText getCostField() {
		return costField;
	}

	public void setCostField(EditText costField) {
		this.costField = costField;
	}

}
